import { createRouter, createWebHashHistory, createWebHistory } from "vue-router";
import { useStore } from "@/store/store.js";
import axios from 'axios'

const router = createRouter({
    history: createWebHistory(),
    routes: [{
            path: '/',
            component: () =>
                import ('../views/home.vue')
        },
        // { path: '/menu1', component: () =>
        //         import ('../views/menu1.vue') },
        // { path: '/menu2', component: () =>
        //         import ('../views/menu2.vue') },
        // { path: '/menu3', component: () =>
        //         import ('../views/menu3.vue') },
        {
            path: '/about',
            component: () =>
                import ('../views/about.vue')
        },
        {
            path: '/login',
            component: () =>
                import ('../views/login.vue')
        },
        {
            path: '/404',
            component: () =>
                import ('../views/404.vue')
        }
    ]
});

//全局守卫
router.beforeEach((to, from, next) => {
    console.log(to); //去往哪个页面
    console.log(from); //来自哪个页面
    const store = useStore();
    //console.log(store);
    let menuList = store.menuList;
    let token = store.token || '';
    if (token) {
        if (to.path == '/login') {
            next({
                path: '/' //进入登录页面
            })
        } else {

            if (menuList && menuList.length>0) {
                next();
            } else {
                axios.post("/api/menu").then((res) => {
                    //console.log(res); //这里返回的就是我们在mock中自定义的数据
                    var menu = res.data.data.menuList;
                    store.menuList = menu;
                    var menus = [];
                    for (let i = 0; i < menu.length; i++) {
                        const m = menu[i];
                        menus.push({
                            path: m.path,
                            component: () =>
                                import (m.address)
                        });
                    }
                    // 动态添加可访问路由表
                    menus.forEach((item) => {
                        router.addRoute(item);
                    });
                    router.addRoute({
                        path: '/:catchAll(.*)',
                        redirect: '/404'
                    });
                    console.log(menus);
                    console.log(router);
                    //跳转
                    next({ to, replace: true })
                });
            }
        }
    } else {
        if (to.path == '/login') {
            next();
        } else {
            next(`/login?redirect=${to.path}`)
        }
    }



});

export default router